//
//  CitesViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-10-27.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "CitesViewController.h"
#import "VisitorViewController.h"
#import "CitesModel.h"
#import "RegisterHelper.h"
#import "CitesTableView.h"
#import "CustomSearchTextField.h"
#import "ChineseInclude.h"
#import "PinYinForObjc.h"

@interface CitesViewController ()<UITableViewEventsDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,UITextFieldDelegate>
{
    BOOL _isMore;
    NSString *pageNum;
}
@property(strong,nonatomic)BMKPoiSearch *poisearch;
@property(strong,nonatomic)BMKGeoCodeSearch*geocodesearch;
@property(strong,nonatomic)CitesTableView *citesTableView;
@property(strong,nonatomic)BMKNearbySearchOption *citySearchOption;
@property(nonatomic, strong)NSString *currentGPSCity;//GPS定位到的城市
@property(nonatomic,strong)UIButton *rightButton;

@property(nonatomic,strong)NSString *poiComnityName;//百度小区名字
@property(nonatomic,strong)NSString *poiAddress;//百度小区地址
@property(nonatomic,strong)CustomSearchTextField *searchText;

@end

@implementation CitesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleView:@"选择小区"];
    self.view.backgroundColor = [UIColor whiteColor];
   
    _data = [[NSMutableArray alloc] initWithCapacity:0];
    
    
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _poisearch = [[BMKPoiSearch alloc]init];
    
     _isMore = NO;
    pageNum = @"0";
    [self startRequestDataWithcity:NO];
    
    [self initWithView];
    
    // Do any additional setup after
    
}


-(void)initWithView{
    
    //签到
    _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightButton.frame = CGRectMake(0,0,80,40);
    [_rightButton setTitle:@"附近" forState:UIControlStateNormal];
    _rightButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_rightButton addTarget:self action:@selector(nearbyAction:) forControlEvents:UIControlEventTouchUpInside];
    [_rightButton setTitleEdgeInsets:UIEdgeInsetsMake(2, 50, 0, 0)];
    _rightButton.titleLabel.textAlignment = NSTextAlignmentRight;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:_rightButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    _searchText = [[CustomSearchTextField alloc] initWithFrame:CGRectMake(0, 0, kWidth, 40)];
    _searchText.delegate = self;
    [self.view addSubview:_searchText];
    [self.searchText addTarget:self action:@selector(editChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.searchText addTarget:self action:@selector(editDidBegin:) forControlEvents:UIControlEventEditingDidBegin];
    
    _citesTableView = [[CitesTableView alloc]initWithFrame:CGRectMake(0, _searchText.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - 44 - _searchText.height) style:UITableViewStylePlain];
    _citesTableView.isNeedTorefresh = YES;
    _citesTableView.eventsDelegate = self;
    _citesTableView.isMore = YES;
    _citesTableView.type = @"附近";
    if ([_rightButton.titleLabel.text isEqual:@"附近"]) {
        _citesTableView.type = @"附近";
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        _citesTableView.type = @"推荐";
    }
    _citesTableView.userInteractionEnabled = YES;
    [self.view addSubview:_citesTableView];


}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
       _geocodesearch.delegate = self;
       _poisearch.delegate = self;

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
        _geocodesearch.delegate = nil;
        _poisearch.delegate = nil;

}

//反编译
-(void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{

    NSLog(@"****%@^^^",result);
}

#pragma mark - BMKGeoCodeSearchDelegate
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        _cityText = result.addressDetail.city;
        _curPage = 0;
        _citySearchOption = [[BMKNearbySearchOption alloc]init];
        _citySearchOption.pageIndex = _curPage;
        _citySearchOption.pageCapacity = 10;
        _citySearchOption.location= result.location;
        _citySearchOption.keyword = @"小区";
        _citySearchOption.sortType = BMK_POI_SORT_BY_DISTANCE;
        _citySearchOption.radius = 1000;
        _citySearchOption.sortType = BMK_POI_SORT_BY_DISTANCE;
        BOOL flag = [_poisearch poiSearchNearBy:_citySearchOption];
        if(flag)
        {
            NSLog(@"城市内检索发送成功");
        }
        else
        {
            NSLog(@"城市内检索发送失败");
        }
        
    }
    else{
        [self showToastMessage:@"地址解析失败"];
    }
}

-(void)getPoiPageData{
    
     [_citesTableView setType:@"推荐"];
    [self showProgressHUD];
    _citySearchOption.pageIndex = _curPage;
    _citySearchOption.pageCapacity = 10;
    BMKUserLocation *userLocation = [AppDelegate sharedDelegate].userlocation;
    _citySearchOption.location = userLocation.location.coordinate;
    _citySearchOption.keyword = @"小区";
    _citySearchOption.radius = 1000;
//    _citySearchOption.sortType = BMK_POI_SORT_BY_DISTANCE;
    BOOL flag = [_poisearch poiSearchNearBy:_citySearchOption];
    if(flag)
    {
        NSLog(@"城市内检索发送成功");
    }
    else
    {
        NSLog(@"城市内检索发送失败");
    }
    [_citesTableView doneLoadingTableViewData];
    [_citesTableView reloadData];
}

#pragma mark  eventsDelegate
- (void)pullUp:(BaseTableView *)baseTableView{
    
    
    if ([_rightButton.titleLabel.text isEqual:@"附近"]) {
        
        _citesTableView.type = @"附近";
        [self startRequestDataWithcity:YES];
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        
        _isMore = YES;
        _citesTableView.type = @"推荐";
       [self getPoiPageData];
        
    }
}

- (void)pullDown:(BaseTableView *)baseTableView{
    
  
    
    if ([_rightButton.titleLabel.text isEqual:@"附近"]) {
        
        pageNum = @"0";
        [self startRequestDataWithcity:NO];
        _citesTableView.type = @"附近";
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        
        _curPage = 0;
        _isMore = NO;
        _citesTableView.type = @"推荐";
        [self getPoiPageData];
        
    }
}


//返回POI搜索结果
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    NSLog(@"%@",result);
    [self hideProgressHUD];
    if (error == BMK_SEARCH_NO_ERROR) {
        
        if (result.poiInfoList.count < 10) {
            _citesTableView.isMore = NO;
        }else{
            _citesTableView.isMore = YES;
            
            _curPage++;
            
        }
        if (!_isMore) {
            [_data removeAllObjects];
        }
        for (int i = 0; i < result.poiInfoList.count; i++) {
            
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            CitesModel* model = [[CitesModel alloc] init];
            model.comnityName = poi.name;
            model.address = poi.address;
            [_data addObject:model];
        }
        _citesTableView.data = _data;
        [_citesTableView doneLoadingTableViewData];
        [_citesTableView reloadData];
        
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
        [_data removeAllObjects];
        _citesTableView.data = _data;
        [_citesTableView reloadData];
    }
}



#pragma mark 附近小区&推荐小区
-(void)nearbyAction:(UIButton *)sender{
    
    if ([sender.titleLabel.text isEqual:@"推荐"]) {
        
        pageNum = @"0";
        [self startRequestDataWithcity:NO];
        [sender setTitle:@"附近" forState:UIControlStateNormal];
        
    }else if ([sender.titleLabel.text isEqual:@"附近"]){

        [sender setTitle:@"推荐" forState:UIControlStateNormal];
        
        BMKUserLocation *userLocation = [AppDelegate sharedDelegate].userlocation;
        [self showProgressHUD];
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        if (userLocation) {
            pt = userLocation.location.coordinate;
        }
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
            [self hideProgressHUD];
        }

        [self getPoiPageData];
    }
    
}


//用户登录
#pragma mark 保存选择小区
-(void)saveCitesId{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *provinceName;
    NSString *cityName;
    [params setValue:[RegisterHelper shareHelper].userId forKey:@"userId"];

    
    if ([_rightButton.titleLabel.text isEqual:@"附近"]) {
        
        [params setValue:[RegisterHelper shareHelper].citesId forKey:@"cid"];
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        
        NSArray *location = [[RegisterHelper shareHelper].location componentsSeparatedByString:@","];
        
        if (location.count != 0 || ![location isEqual:[NSNull null]]) {
            
            provinceName = location[0];
            cityName = location[1];
            
            [params setValue:provinceName forKey:@"provinceName"];
            [params setValue:cityName forKey:@"cityName"];
            [params setValue:_poiComnityName forKey:@"comnityName"];
            [params setValue:_poiAddress forKey:@"address"];
        }
    }
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kChangeCid
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             
                             BOOL result = [[responseDic objectForKey:@"result"] boolValue];
                             if (result == 0) {
                                 DLog(@"数据获取成功 %@",responseDic);
                             }
                             [RegisterHelper shareHelper].citesId = [responseDic objectForKey:@"cid"];
                         }
                         else{
                             
                             DLog(@"获取数据失败  %@",response.errorMessage);
                         }
                         
                         [_citesTableView reloadData];
                     }];
}

//游客登录
-(void)startRequestDataWithcity:(BOOL)isNearMore{
    
    [_citesTableView setType:@"附近"];
    
    NSString *page = pageNum;
    NSString *pageSize = @"10";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"440300" forKey:@"cityCode"];
    [params setValue:page forKey:@"page"];
    [params setValue:pageSize forKey:@"pageSize"];
    
    __weak VisitorViewController *weak_self = self;
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kcites
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         [_citesTableView doneLoadingTableViewData];
                         
                         if(!response.isError){
                             NSDictionary *responseDic = request.responseJSON;
                             
                             BOOL result = [[responseDic objectForKey:@"result"] boolValue];
                             if (result == 0) {
                                 DLog(@"数据获取成功 %@",responseDic);
                                 NSArray *list = [responseDic objectForKey:@"list"];
                                 
                                 
                                 NSDictionary *responseDic = request.responseJSON;
                                 DLog(@"成功数据:%@",responseDic);
                                 
                                 if (list.count < 10) {
                                     _citesTableView.isMore = NO;
                                 }else{
                                     _citesTableView.isMore = YES;
                                     
                                     int currentPage = [pageNum intValue];
                                     pageNum = [NSString stringWithFormat:@"%d",currentPage+1];
                                     
                                 }
                                 
                                 if (!isNearMore) {
                                     [_data removeAllObjects];
                                 }

                                 for (NSDictionary *dic in list) {
                                     
                                     CitesModel *citesModel = [[CitesModel alloc]initWithCitesInfo:dic];
                                     [_data addObject:citesModel];
                                     NSLog(@"data:%@",_data);
                                 }
                                 _citesTableView.data = _data; 
                             }
                             [_citesTableView reloadData];
                         }
                         else{
                             
                             DLog(@"获取数据失败  %@",response.errorMessage);
                         }

                     }];

}

-(void)basetableView:(BaseTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CitesModel *citesModel = [_data objectAtIndex:indexPath.row];
    
    NSLog(@"name:%@,address:%@",citesModel.comnityName,citesModel.address);
    
    if ([_rightButton.titleLabel.text isEqual:@"附近"]) {
        
        [RegisterHelper shareHelper].citesName = citesModel.comnityName;
        [RegisterHelper shareHelper].citesId = citesModel.comnitId;
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        
        _poiAddress = citesModel.address;
        _poiComnityName = citesModel.comnityName;
        [RegisterHelper shareHelper].citesName = citesModel.comnityName;
    }

    if ([APP_DELEGATE isLogin]) {
        [self saveCitesId];
    }
    
    if (!_isRegister) {
        [APP_DELEGATE initMainViewControllerWithStoryBoardIdentifier:@"MainViewController" type:0 pushIn:self];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}



#pragma textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    int MAX_CHARS = 40;
    NSMutableString *newtxt = [NSMutableString stringWithString:textField.text];
    [newtxt replaceCharactersInRange:range withString:string];
    return ([newtxt length] <= MAX_CHARS);
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    [self searchResult:textField.text];
    
    return YES;
}

- (void)editDidBegin:(UITextField *)textField
{
    NSString * searchText = textField.text;
    NSLog(@"searchText:%@",searchText);
    
    
    if (searchText.length == 0) {
        [self.data removeAllObjects];
        
        
        if ([_rightButton.titleLabel.text isEqual:@"附近"]) {
            
            pageNum = @"0";
            [self startRequestDataWithcity:NO];
            _citesTableView.type = @"附近";
            
        }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
            
            _curPage = 0;
            _isMore = NO;
            _citesTableView.type = @"推荐";
            [self getPoiPageData];
            
        }

    }else{
        
        [self searchResult:searchText];

    }
}

- (void)editChanged:(UITextField *)textField
{
    NSString * searchText = textField.text;
    NSLog(@"searchText:%@",searchText);
    
    [self nearbyAction:nil ];
    
    if ([_rightButton.titleLabel.text isEqual:@"附近"])
    {
         if (searchText.length == 0) {
             
             pageNum = @"0";
             [self startRequestDataWithcity:NO];
             _citesTableView.type = @"附近";
         }else{
             
             [self searchResult:searchText];
             
         }
        
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        
        if (searchText.length == 0) {
            
            _curPage = 0;
            _isMore = NO;
            _citesTableView.type = @"推荐";
            [_data removeAllObjects];
            [self getPoiPageData];

            
        }else{
            
            [self searchResult:searchText];
            
        }
    }

   
}



-(void)searchResult:(NSString*)result{
    if(result == nil || [result isEqualToString:@""])
        return;
    
    if ([_rightButton.titleLabel.text isEqual:@"附近"])
    {
        
        
    }else if ([_rightButton.titleLabel.text isEqual:@"推荐"]){
        
       [self searchTableView:result];
    }
//    [self nearbyAction:nil];
    
  NSMutableArray  *searchResults = [[NSMutableArray alloc]init];
    if (result.length>0&&![ChineseInclude isIncludeChineseInString:result]) {
        for (int i=0; i<_data.count; i++) {
            
            CitesModel *citesModel = _data[i];
            
            if ([ChineseInclude isIncludeChineseInString:citesModel.comnityName]) {
                NSString *tempPinYinStr = [PinYinForObjc chineseConvertToPinYin:citesModel.comnityName];
                NSRange titleResult=[tempPinYinStr rangeOfString:result options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    [searchResults addObject:_data[i]];
                }
                NSString *tempPinYinHeadStr = [PinYinForObjc chineseConvertToPinYinHead:citesModel.comnityName];
                NSRange titleHeadResult=[tempPinYinHeadStr rangeOfString:result options:NSCaseInsensitiveSearch];
                if (titleHeadResult.length>0) {
                    [searchResults addObject:_data[i]];
                }
            }
            else {
                NSRange titleResult=[citesModel.comnityName rangeOfString:result options:NSCaseInsensitiveSearch];
                if (titleResult.length>0) {
                    [searchResults addObject:_data[i]];
                }
            }
        }
    } else if (result.length>0&&[ChineseInclude isIncludeChineseInString:result]) {
        for (CitesModel *tempStr in _data) {
            
            NSRange titleResult=[tempStr.comnityName rangeOfString:result options:NSCaseInsensitiveSearch];
            if (titleResult.length>0) {
                [searchResults addObject:tempStr];
            }
        }
    }
    
        _citesTableView.data = searchResults;
        [_citesTableView doneLoadingTableViewData];
        [_citesTableView reloadData];
        _citesTableView.moreButton.hidden = NO;
    
}

-(void)searchTableView:(NSString *)result{
    
    [_citesTableView setType:@"推荐"];
    [self showProgressHUD];
    _citySearchOption.pageIndex = _curPage;
    _citySearchOption.pageCapacity = 10;
    BMKUserLocation *userLocation = [AppDelegate sharedDelegate].userlocation;
    _citySearchOption.location = userLocation.location.coordinate;
    _citySearchOption.keyword =[NSString stringWithFormat:@"%@",result];
    _citySearchOption.radius = 10000;
    _citySearchOption.sortType = BMK_POI_SORT_BY_DISTANCE;
    BOOL flag = [_poisearch poiSearchNearBy:_citySearchOption];
    if(flag)
    {
        NSLog(@"城市内检索发送成功");
    }
    else
    {
        NSLog(@"城市内检索发送失败");
    }
    
    [_citesTableView doneLoadingTableViewData];
    [_citesTableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
